import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Button, message, Select, DatePicker, Input, Modal } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { useRequest } from '@umijs/hooks';
import ProTable from '@ant-design/pro-table';
import AuthComponent from '@/components/Authorized/AuthComponent';
import router from 'umi/router';
import styles from './index.less';
import moment from 'moment';
import LuggageAddOrEditForm from './components/LuggageAddOrEditForm'
import { save, list, update, updateCount, batchDelete, getDetail } from './service';

// 变量
let hiddenData = {}

const { Option } = Select;

const LuggageManagement = () => {

  const actionRef = useRef();
  const ref = useRef()

  // 表格高度
  const [height, controlH] = useState(300)
  const [isCollapse, controlC] = useState(true);
  // 新增、编辑弹窗显隐
  const [luggageAddOrEditVisible, handleLuggageAddOrEditVisible] = useState(false)
  // 弹窗title
  const [modalTitle, handleModalTitle] = useState('')
  // 箱包id
  const [luggageId, handleLuggageId] = useState('')
  // 箱包当前数据
  const [luggageData, handleLuggageData] = useState({})
  // 多选
  const [selectedRowKeys, handleSelectedRowKeys] = useState([])

  // 单个删除接口
  const { run: updateR } = useRequest(params => update(params), {
    manual: true,
    onSuccess: (res) => {
      message.success('删除成功')
      actionRef.current.reload()
    }
  })
  // 批量删除接口
  const { run: batchDeleteR } = useRequest(params => batchDelete(params), {
    manual: true,
    onSuccess: (res) => {
      message.success('删除成功')
      actionRef.current.reload()
    }
  })
  // 获取箱包详细信息接口
  const { run: getDetailR, data: getDetailD = '' } = useRequest(params => getDetail(params), {
    manual: true,
    onSuccess: (res) => {
      console.log(res)
    }
  })

  // 筛选栏箱包单价规则
  const luggagePriceValidator = (value, onChange) => {
    onChange(value.replace(/\D/g, ''))
  }

  // 统计开始时间禁用
  const disabledStatisticsStartDate = (current) => {
    return ref.current.getFieldsValue().endTime && current && moment(current).endOf('day') > ref.current.getFieldsValue().endTime.endOf('day');
  }

  // 统计结束时间禁用
  const disabledStatisticsEndDate = (current) => {
    return ref.current.getFieldsValue().startTime && current && moment(current).endOf('day') < ref.current.getFieldsValue().startTime.endOf('day');
  }

  // 点击搜索
  const beforeSearchSubmit = params => {

    if (!params.startTime) delete params.startTime;
    if (!params.endTime) delete params.endTime;

    if (!isCollapse) {
      getDetailR({ startTime: params.startTime, endTime: params.endTime, serviceCity: 'CTU' })
      return params
    } else {
      if (event.target.querySelector('span').innerText === '查 询') {
        if (Object.keys(params).indexOf('pkgNo') === -1) {
          params.pkgNo = ''
        }
        if (Object.keys(params).indexOf('pkgName') === -1) {
          params.pkgName = ''
        }
        getDetailR({ startTime: hiddenData.startTime, endTime: hiddenData.endTime, serviceCity: 'CTU' })
        return { ...hiddenData, ...params }
      } else if (event.target.querySelector('span').innerText === '重 置') {
        hiddenData = {}
        getDetailR({})
        return params
      }
    }
  }

  // 多选改变时方法
  const onSelectChange = selectedRowKeys => {
    handleSelectedRowKeys(selectedRowKeys)
  };

  // 多选
  const rowSelection = {
    selectedRowKeys,
    onChange: onSelectChange
  };

  // 清空选择性
  const clearSelection = () => {
    handleSelectedRowKeys([])
  };

  // 新增
  const add = (selectedRows) => {
    handleModalTitle('新增箱包')
    handleLuggageId('')
    handleLuggageData({})
    handleLuggageAddOrEditVisible(true)
  }

  // 编辑
  const edit = (selectedRows) => {
    handleModalTitle('编辑箱包')
    if (selectedRows.length !== 1) {
      message.warning('请选择一项')
    } else {
      handleLuggageData(selectedRows[0])
      handleLuggageId(selectedRows[0].id)
      handleLuggageAddOrEditVisible(true)
    }
  }

  // 新增/编辑回调
  const handleLuggage = async fields => {
    try {
      if (luggageId === '') {
        await save(fields)
      } else {
        if (modalTitle === '新增箱包') {
          await updateCount({ ...fields, id: luggageId, del: 0 })
        } else {
          await update({ ...fields, id: luggageId, del: 0 })
        }
      }
      return true
    } catch (error) {
      if (luggageId === '') {
        message.error('新增失败请重试！');
      } else {
        if (modalTitle === '新增箱包') {
          message.error('新增失败请重试！');
        } else {
          message.error('修改失败请重试！');
        }
      }
      return false
    }
  }

  // 删除
  const del = (selectedRows) => {
    if (selectedRows.length === 0) {
      message.warning('请至少选择一项')
    } else {
      Modal.confirm({
        title: '删除',
        content: '确认删除该数据？',
        okText: '确认',
        cancelText: '取消',
        onOk: () => {
          let ids = []
          selectedRows.map(item => {
            ids.push(item.id)
          })
          if (selectedRows.length === 1) {
            updateR({ id: ids.join(','), del: 1 })
          } else {
            batchDeleteR({ ids: ids.join(',') })
          }
        }
      });
    }
  }

  // 增量
  const increment = (selectedRows) => {
    handleModalTitle('新增箱包')
    if (selectedRows.length !== 1) {
      message.warning('请选择一项')
    } else {
      handleLuggageId(selectedRows[0].id)
      handleLuggageData(selectedRows[0])
      handleLuggageAddOrEditVisible(true)
    }
  }

  useEffect(() => {
    if (isCollapse) {
      controlH(document.body.clientHeight - 520);
    } else {
      controlH(document.body.clientHeight - 595);
    }
  }, [isCollapse])

  // 切换tab清空搜索
  useEffect(() => {
    getDetailR({})
    hiddenData = {}
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [])

  const columns = [
    {
      title: '箱包编号',
      dataIndex: 'pkgNo',
      width: 120
    },
    {
      title: '箱包名称',
      dataIndex: 'pkgName',
      width: 140
    },
    {
      title: '箱包尺寸',
      dataIndex: 'pkgSize',
      width: 120
    },
    {
      title: '箱包单价',
      dataIndex: 'pkgPriceLow',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Input placeholder='最低' onChange={(e) => luggagePriceValidator(e.target.value, onChange)}></Input>
        );
      },
      hideInTable: true
    },
    {
      title: '',
      dataIndex: '12',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <span>-</span>
        );
      },
      hideInTable: true
    },
    {
      title: '',
      dataIndex: 'pkgPriceHigh',
      width: 120,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Input placeholder='最高' onChange={(e) => luggagePriceValidator(e.target.value, onChange)}></Input>
        );
      },
      hideInTable: true
    },
    {
      title: '箱包单价',
      dataIndex: 'pkgPrice',
      width: 120,
      hideInSearch: true
    },
    {
      title: '箱包库存数量',
      dataIndex: 'stockCount',
      width: 120,
      hideInSearch: true
    },
    {
      title: '服务航站',
      dataIndex: 'pkgStation',
      width: 200,
      renderFormItem: (_, { onChange, value }) => {
        return (
          <Select
            allowClear={true}
            showSearch
            placeholder='请选择'
            filterOption={true}
            optionFilterProp="children"
            onChange={onChange}
            value={value ? value : '0'}
          >
            <Option key='0'>CTU-双流国际机场</Option>
          </Select>
        );
      },
      hideInTable: true
    },
    {
      title: '统计开始日期',
      dataIndex: 'startTime',
      width: 200,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            disabledDate={disabledStatisticsStartDate}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '统计结束日期',
      dataIndex: 'endTime',
      width: 200,
      renderFormItem: (_, { onChange, value, ...rest }) => {
        const format = 'YYYY-MM-DD';
        return (
          <DatePicker
            onChange={onChange}
            format={format}
            value={value}
            disabledDate={disabledStatisticsEndDate}
            {...rest}
          />
        );
      },
      hideInTable: true
    },
    {
      title: '服务航站',
      dataIndex: 'serviceCity',
      width: 120,
      hideInSearch: true
    },
    {
      title: '采购箱包数量',
      dataIndex: 'pkgCount',
      width: 120,
      hideInSearch: true
    },
    {
      title: '已赔付箱包数量',
      dataIndex: 'payCount',
      width: 140,
      hideInSearch: true
    },
    {
      title: '创建人',
      dataIndex: 'createUser',
      width: 140,
      hideInSearch: true
    },
    {
      title: '更新人',
      dataIndex: 'updateUser',
      width: 140,
      hideInSearch: true
    },
    {
      title: '更新时间',
      dataIndex: 'updateTime',
      width: 160,
      hideInSearch: true
    }
  ];

  return (
    <>
      <ProTable
        actionRef={actionRef}
        formRef={ref}
        rowKey="id"
        className={styles.luggageManagement}
        headerTitle={
          <div>
            <span style={{ fontWeight: "700", color: "rgba(0,0,0,0.85)", fontSize: '16px' }}>箱包信息数据列表</span>
          </div>
        }
        options={{ fullScreen: true, reload: false, setting: true, density: false }}
        rowSelection={rowSelection}
        beforeSearchSubmit={beforeSearchSubmit}
        search={{
          span: 6,
          onCollapse: val => {
            controlC(val)
            if (!val && hiddenData) {
              ref.current.setFieldsValue({
                pkgPriceLow: hiddenData.pkgPriceLow,
                pkgPriceHigh: hiddenData.pkgPriceHigh,
                pkgStation: hiddenData.pkgStation,
                startTime: hiddenData.startTime,
                endTime: hiddenData.endTime
              })
            } else {
              hiddenData = ref.current.getFieldsValue()
            }
          }
        }}
        toolBarRender={(action, { selectedRows }) => [
          <AuthComponent authCode='luggageManagement.page.basic'>
            <Button type="primary" onClick={() => add(selectedRows)} size="small">
              新增
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='luggageManagement.page.edit'>
            <Button type="primary" onClick={() => edit(selectedRows)} size="small">
              修改
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='luggageManagement.page.del'>
            <Button type="primary" onClick={() => del(selectedRows)} size="small">
              删除
            </Button>
          </AuthComponent>,
          <AuthComponent authCode='luggageManagement.page.basic'>
            <Button type="primary" onClick={() => increment(selectedRows)} size="small">
              增量
            </Button>
          </AuthComponent>
        ]}
        tableAlertRender={({ selectedRowKeys, selectedRows, onCleanSelected }) => (
          <span>{getDetailD}</span>
        )}
        tableAlertOptionRender={false}
        request={params => {
          clearSelection()
          return list(params)
        }}
        columns={columns}
        pagination={{
          showSizeChanger: true,
          showQuickJumper: true,
          showTotal: (total, range) => `第${range[0]}-${range[1]}条 共 ${total} 项`,
          defaultPageSize: 20,
          pageSizeOptions: ['20', '30', '40']
        }}
        scroll={{ x: 900, y: height }}
      />
      {
        luggageAddOrEditVisible && <LuggageAddOrEditForm
          onSubmit={async value => {
            const success = await handleLuggage(value)
            if (success) {
              if (luggageId === '') {
                message.success('新增成功')
              } else {
                if (modalTitle === '新增箱包') {
                  message.success('新增成功')
                } else {
                  message.success('编辑成功')
                }
              }
              handleLuggageAddOrEditVisible(false)
              actionRef.current.reload()
            }
          }}
          onCancel={() => handleLuggageAddOrEditVisible(false)}
          luggageAddOrEditVisible={luggageAddOrEditVisible}
          modalTitle={modalTitle}
          luggageId={luggageId}
          luggageData={luggageData}
        ></LuggageAddOrEditForm>
      }
    </>
  );
};

export default Form.create()(LuggageManagement);
